package com.example.interviewrecorder.view

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.interviewrecorder.LyyBaseActivity
import com.example.interviewrecorder.LyyDatabase
import com.example.interviewrecorder.R
import com.example.interviewrecorder.components.showTip
import com.example.interviewrecorder.dao.LyyUserDao
import com.example.interviewrecorder.dao.SecurityQuestionDao
import com.example.interviewrecorder.databinding.ActivityFindPasswordBinding
import com.example.interviewrecorder.model.LyyUser
import com.example.interviewrecorder.model.SecurityQuestion
import com.example.interviewrecorder.utils.LyyActivityCollector
import com.example.interviewrecorder.utils.LyyLogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class FindPasswordActivity : LyyBaseActivity(), View.OnClickListener {
    private val mBinding: ActivityFindPasswordBinding by lazy {
        ActivityFindPasswordBinding.inflate(layoutInflater)
    }

    private val lyyUserDao: LyyUserDao = LyyDatabase.getDatabase().getLyyUserDao()

    private val securityQuesitonDao: SecurityQuestionDao =
        LyyDatabase.getDatabase().getSecurityQuestionDao()

    private lateinit var currState: STATE

    //想要找回密码的用户
    private lateinit var findedUser: LyyUser

    //密保问题列表
    private lateinit var securityQuestionList: List<SecurityQuestion>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBinding.root)
        initViews()
        initEvents()
    }

    private fun initEvents() {
        mBinding.submitBtn.setOnClickListener(this)
    }

    private fun initViews() {
        currState = STATE.USERNAME_STATE
        updateView()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.submitBtn -> {
                when (currState) {
                    //下一步
                    STATE.USERNAME_STATE -> {
                        onNextStepClick()
                    }
                    //提交
                    else -> {
                        onSubmitClick()
                    }
                }
            }
        }
    }

    fun onNextStepClick() {
        lifecycleScope.launch {
            launch(Dispatchers.IO) {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    runCatching {
                        val username = mBinding.usernameRight.text.toString()
                        val user = lyyUserDao.findUserByUsername(username)
                        LyyLogUtil.d(TAG, "findUserByUsername success, user=$user")
                        if (user == null) {
                            runOnUiThread {
                                showTip(content = getString(R.string.find_user_fail_by_username_tip))
                            }
                            return@runCatching
                        }
                        findedUser = user

                        val list = securityQuesitonDao.querySQByUserId(user.id)
                        securityQuestionList = list
                        val securityQuesitonOne = list[0]
                        val securityQuesitonTwo = list[1]
                        val securityQuesitonThree = list[2]
                        if (securityQuesitonOne.quesiton.isBlank() && securityQuesitonOne.answer.isBlank() && securityQuesitonTwo.quesiton.isBlank() && securityQuesitonTwo.answer.isBlank() && securityQuesitonThree.quesiton.isBlank() && securityQuesitonThree.answer.isBlank()) {
                            runOnUiThread {
                                showTip(content = getString(R.string.not_set_security_question_can_not_find_password_tip))
                            }
                            return@runCatching
                        }
                        currState = STATE.SECURITY_QUESTION_STATE
                        updateView()
                        updateSecurityQuestionView(list)
                    }.onFailure {
                        LyyLogUtil.e(TAG, it.toString())
                    }
                }
            }
        }

    }

    fun onSubmitClick() {
        if (::findedUser.isInitialized && ::securityQuestionList.isInitialized) {

            val securityQuesitonOne = securityQuestionList[0]
            val securityQuesitonTwo = securityQuestionList[1]
            val securityQuesitonThree = securityQuestionList[2]

            val answer1 = mBinding.answerOneRight.text.toString()
            val answer2 = mBinding.questionTwoRight.text.toString()
            val answer3 = mBinding.answerThreeRight.text.toString()

            if (securityQuesitonOne.answer != answer1 || securityQuesitonTwo.answer != answer2 || securityQuesitonThree.answer != answer3) {
                showTip(content = getString(R.string.security_question_answer_not_correct_tip))
                return
            }
            showTip(
                content = String.format(
                    getString(R.string.find_password_success_tip),
                    findedUser.userName,
                    findedUser.password
                )
            )
        }
    }

    fun updateView() {
        runOnUiThread {
            when (currState) {
                STATE.USERNAME_STATE -> {
                    mBinding.contentCl0.visibility = View.VISIBLE
                    mBinding.contentCl1.visibility = View.GONE
                    mBinding.contentCl2.visibility = View.GONE
                    mBinding.contentCl3.visibility = View.GONE
                    mBinding.submitBtn.setText(getString(R.string.next_step_text))
                }

                else -> {
                    mBinding.contentCl0.visibility = View.GONE
                    mBinding.contentCl1.visibility = View.VISIBLE
                    mBinding.contentCl2.visibility = View.VISIBLE
                    mBinding.contentCl3.visibility = View.VISIBLE
                    mBinding.submitBtn.setText(R.string.submit_text)
                }
            }
        }
    }

    fun updateSecurityQuestionView(list: List<SecurityQuestion> = listOf<SecurityQuestion>()) {
        runOnUiThread {
            val securityQuesitonOne = list[0]
            val securityQuesitonTwo = list[1]
            val securityQuesitonThree = list[2]

            mBinding.questionOneRight.setText(securityQuesitonOne.quesiton)
            mBinding.questionTwoRight.setText(securityQuesitonTwo.quesiton)
            mBinding.questionThreeRight.setText(securityQuesitonThree.quesiton)
        }
    }

    companion object {
        private const val TAG = "FindPasswordActivity"
        fun start() {
            val currAct = LyyActivityCollector.getCurrActivity()
            val intent = Intent(currAct, FindPasswordActivity::class.java)
            currAct.startActivity(intent)
        }
    }

    enum class STATE {
        USERNAME_STATE, SECURITY_QUESTION_STATE
    }
}